package org.tuestudent.grouppa;

import org.tuestudent.grouppa.ChangePinPopup.OnPinChangeListener;
import org.tuestudent.grouppa.LoginViewController.GetProfileResponse;

import android.animation.AnimatorSet.Builder;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

// Popup with information presenting the user data
public class UserProfile extends DialogFragment implements OnClickListener, OnPinChangeListener {

    private static UserProfile instance = null;
    public static UserProfile getInstance()
    {
        return instance;
    }
      
    // Initialization and declaration of variables
    View mainView;
    EditText nicknameView;
    EditText emailView;
    EditText phoneView;
    EditText extraView;
    Button saveChangesButton;
    Button changePinButton;
    ImageButton cancel;
    User userdata;
    
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        ContextThemeWrapper cw =
                new ContextThemeWrapper(getActivity(), R.style.AlertDialogTheme);
        final AlertDialog.Builder builder = new AlertDialog.Builder(cw);
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        mainView = inflater.inflate(R.layout.popup_profile, null);
        nicknameView = (EditText) mainView.findViewById(R.id.userInfoNickname);
        emailView = (EditText) mainView.findViewById(R.id.userInfoEmail);
        phoneView = (EditText) mainView.findViewById(R.id.userInfoPhone);
        extraView = (EditText) mainView.findViewById(R.id.userInfoExtra);
        saveChangesButton = (Button) mainView.findViewById(R.id.userInfoSaveChangesButton);
        saveChangesButton.setOnClickListener(this);
        
        cancel = (ImageButton) mainView.findViewById(R.id.cancelButton);
        cancel.setOnClickListener(this);
        
        changePinButton = (Button) mainView.findViewById(R.id.userInfoChangePinButton);
        changePinButton.setOnClickListener(this);
        
        builder.setView(mainView);
        LoginViewController.getInstance().getProfile(Main.getContext().currentUserName);
        return builder.create();
        
    }
    
    /**
     * Method that handles the data retrieved by the server
     * 
     * @param response
     */
    public void onGetProfileResponse(GetProfileResponse response) {
        userdata = response.userdata;
        nicknameView.setText(userdata.name);
        emailView.setText(userdata.email);
        if(userdata.phone == null){
            phoneView.setHint("0612345670");
        } else {
            phoneView.setText(userdata.phone);
        }
        if(userdata.extraInfo == null){
            extraView.setHint("Enter extra information");
        } else {
            extraView.setText(userdata.extraInfo);
        }
        
    }
    
    // On the start of the fragment data is retrieved from the views
    @Override
    public void onStart() {
        super.onStart();
        nicknameView = (EditText) mainView.findViewById(R.id.userInfoNickname);
        emailView = (EditText) mainView.findViewById(R.id.userInfoEmail);
        phoneView = (EditText) mainView.findViewById(R.id.userInfoPhone);
        extraView = (EditText) mainView.findViewById(R.id.userInfoExtra);
        saveChangesButton = (Button) mainView.findViewById(R.id.userInfoSaveChangesButton);
        saveChangesButton.setOnClickListener(this);
        instance = this;
    }
    @Override
    public void onStop() {
        super.onStop();
        instance = null;
    }
    /**
     * Takes care of button events and checks if all values are correct
     * 
     * @param v
     */
    @Override
    public void onClick(View v) {
        if( v == saveChangesButton)
        {
            boolean check = true;
            
            if (nicknameView.getText().toString().trim().isEmpty()){
                nicknameView.setError("please enter a valid nickname.");
                check = false;
            }
            else if (nicknameView.getText().toString().trim().equals("you")) {
                nicknameView.setError("Nickname should not be 'you'.");
                check = false;
            }
            else if (!isValid(nicknameView.getText().toString())) {
                nicknameView.setError("nickname may only containt (a-z, A-Z, 0-9)");
                check = false;
            }
            
            else if ( !emailIsValid(emailView.getText().toString())) {
                emailView.setError("Please enter a valid email");
                check = false;
            }
            else if (!phoneView.getText().toString().trim().isEmpty()
                        &&!phoneIsValid(phoneView.getText().toString())){
                phoneView.setError("Please enter a valid phone number (10 digits).");
                check = false;
            }
            
//            submit when the validation is correct.
            if (check) {
                userdata.name = nicknameView.getText().toString();
                userdata.email = emailView.getText().toString();
                if(!phoneView.getText().toString().trim().isEmpty()){
                    userdata.phone = phoneView.getText().toString();
                }
                if(!extraView.getText().toString().trim().isEmpty()){
                    userdata.extraInfo = extraView.getText().toString();   
                }
                LoginViewController.getInstance().changeProfile(userdata);
            }
            
            return;
        }
        if (v == cancel)
        {
            dismiss();
            return;
        }
        if(v == changePinButton)
        {

            ChangePinPopup changePinPopup = new ChangePinPopup(Main.getContext().currentUserPassword, this);
            changePinPopup.show(getFragmentManager(), "changeGroupPin");
        }
        
    }
    // method to check the phone number.
     private boolean phoneIsValid(String phone) {
         return phone.matches("[0-9]+") && phone.length() == 10;
    }
     
    // method to check if an email is not empty and of the right form
    public boolean emailIsValid(String email) {
        return (!email.isEmpty()
                && email.matches("[a-zA-Z0-9\\-\\_\\.]+@[a-zA-Z0-9\\-\\_\\.]+\\.[a-zA-Z0-9]{2,3}"))||
                email.equals("m");
    }
    
    // method to check if a nickname contains only (capital) letters and numbers
    public boolean isValid(String name) {
        return name.matches("[a-zA-Z0-9 ]+");
    }
    
    /**
     * Method showing the user if the information send by the user is retrieved by the server 
     * 
     * @param response
     */
    public void onChangeProfileResponse(GetProfileResponse response) {
        AppContext ctx = Main.getContext();
        ctx.grouppaActivity.turnOffDialogs();
        if(response.succeeded)
        {
            ctx.currentUserPassword = response.userdata.password;
            ctx.currentUserName = response.userdata.name;
            
            ctx.grouppaActivity.actionSuccess("Profile changed succesfully");
        }
        else
        {
            ctx.grouppaActivity.errorPopup("Error during changing profile: "+response.errorReason);
        }
    }
    
    /**
     * called when change pin popup finished
     */
    @Override
    public void pinChange(String newPin, ChangePinPopup popup) {

        userdata.password = newPin;
        LoginViewController.getInstance().changeProfile(userdata);
        Main.getContext().grouppaActivity.busyMessage("Changing user pin...");
    }
}
